# -*- coding: utf-8 -*-
##############################################################################
#
#    OpenERP, Open Source Management Solution
#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as
#    published by the Free Software Foundation, either version 3 of the
#    License, or (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import time
from lxml import etree
from osv import fields, osv
from tools.translate import _
import pooler
from datetime import datetime
from mx import DateTime as dt
from mx.DateTime import RelativeDateTime as rdt
import copy
from operator import itemgetter
from report import report_sxw
import base64
from tools import float_round, float_is_zero, float_compare
from openerp import SUPERUSER_ID
from openerp.tools.translate import _
import xml.etree.ElementTree as ET


class fleet_monitor_import(osv.osv_memory):
    _name = 'fleet.monitor.import'
    _description = 'Fleet Monitor Import'

    def _data_get(self, cr, uid, ids, name, arg, context=None):
        if context is None:
            context = {}
        result = {}
        location = self.pool.get('ir.config_parameter').get_param(cr, uid, 'fleet_monitor_import.location')
        bin_size = context.get('bin_size')
        for attach in self.browse(cr, uid, ids, context=context):
            if location and attach.store_fname:
                result[attach.id] = self._file_read(cr, uid, location, attach.store_fname, bin_size)
            else:
                result[attach.id] = attach.db_datas
        return result

    def _data_set(self, cr, uid, id, name, value, arg, context=None):
        # We dont handle setting data to null
        if not value:
            return True
        if context is None:
            context = {}
        location = self.pool.get('ir.config_parameter').get_param(cr, uid, 'fleet_monitor_import.location')
        file_size = len(value.decode('base64'))
        if location:
            attach = self.browse(cr, uid, id, context=context)
            if attach.store_fname:
                self._file_delete(cr, uid, location, attach.store_fname)
            fname = self._file_write(cr, uid, location, value)
            # SUPERUSER_ID as probably don't have write access, trigger during create
            super(fleet_monitor_import, self).write(cr, SUPERUSER_ID, [id], {'store_fname': fname, 'file_size': file_size}, context=context)
        else:
            super(fleet_monitor_import, self).write(cr, SUPERUSER_ID, [id], {'db_datas': value, 'file_size': file_size}, context=context)
        return True

    _columns = {
        'datas_fname': fields.char('File Name',size=256),
        'type': fields.selection( [ ('url','URL'), ('binary','Binary'), ],
                'Type', help="Binary File or URL", required=True, change_default=True),
        'datas': fields.function(_data_get, fnct_inv=_data_set, string='File Content', type="binary", nodrop=True),
        'store_fname': fields.char('Stored Filename', size=256),
        'db_datas': fields.binary('Database Data'),
        'file_size': fields.integer('File Size'),
        'url': fields.char('Url', size=1024),
    }

    _defaults = {
        'type': 'binary',
        'file_size': 0,
    }

    def test_xml(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        return self.pool.get('fleet.monitor').cronjob_xml_link(cr, uid, ids)

    def import_xml(self, cr, uid, ids, context=None):
        if context is None:
            context = {}
        print 'test'
        new_fleet_monitor = []
        for attach in self.browse(cr, uid, ids, context=context):
            if attach.type == 'url':
                url = attach.url
                if not url.endswith('.xml'):
                    raise osv.except_osv( _('Error!'),
                                          _("The Selected Files is not in xml files type."))

                tree = ET.parse(url)
                root = tree.getroot()
            else:
                datas_fname = attach.datas_fname
                if not datas_fname.endswith('.xml'):
                    raise osv.except_osv( _('Error!'),
                                          _("The Selected Files is not in xml files type."))

                file = base64.decodestring(attach.db_datas)
                root = ET.fromstring(file)
            for child in root:
                if child.tag == 'data':
                    CarNum = child.find('CarNum').text
                    fleet_vehicles = self.pool.get('fleet.vehicle').search(cr, uid, [('license_plate', '=', CarNum)], context=context)
                    if len(fleet_vehicles) > 1:
                        raise osv.except_osv( _('Error!'),
                                 _("Car Number '%s' is more than one at the system."%CarNum))
                    if not fleet_vehicles:
                        raise osv.except_osv( _('Error!'),
                                  _("cannot find Car Number '%s' at the system."%CarNum))
                    new_fleet_monitor.append(self.pool.get('fleet.monitor').create(cr, uid, {
                           'no_fleet':  fleet_vehicles[0],
                           'gps_date': child.find('gps_time').text,
                           'geo_longitude' : child.find('lon').text,
                           'geo_latitude' : child.find('lat').text,
                           'address_id' : child.find('Address').text,
                           'temperature' : child.find('Temperature').text,
                           'start_condition' : child.find('StarCond').text,
                           'speed' : child.find('Speed').text,
                           'direction' : child.find('Direction').text,
                           'mileage' : child.find('Mileage').text,
                           'term_state' : child.find('TerminalStatus').text,
                           'vehicle_type' : child.find('VehicleType').text,
                           'unit_id': child.find('unit_id').text,
                       }))

#                         gps_time = child.find('gps_time').text
#                         lon = child.find('lon').text
#                         lat = child.find('lat').text
#                         Address = child.find('Address').text
#                         Temperature = child.find('Temperature').text
#                         StarCond = child.find('StarCond').text
#                         Speed = child.find('Speed').text
#                         Direction = child.find('Direction').text
#                         Mileage = child.find('Mileage').text
#                         TerminalStatus = child.find('TerminalStatus').text
#                         VehicleType = child.find('VehicleType').text
#                         unit_id = child.find('unit_id').text

#                         print unit_id
#                 for data in root.findall('data'):
#                     gps_time = data.get('gps_time')
                
#                     print gps_time
        domain = []
        domain.append(('id','in', new_fleet_monitor))
        return {
            'domain': str(domain),
            'name': _('Returned Picking'),
            'view_type':'form',
            'view_mode':'tree,form',
            'res_model': 'fleet.monitor',
            'type':'ir.actions.act_window',
            'context':context,
        }


fleet_monitor_import()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
